<template>
  <div ref="mainCon" class="container">
    <topTitle
      v-if="!hiddleToolBar"
      :titleText="titleText"
      :titleExplain="titleExplain"
    ></topTitle>
    <div class="mainCon">
      <div class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-form-item label="黑名单企业" class="row-padding-bottom">
            <el-input
              v-model="filterField.keyword"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="funComBut searchBtn"
            >
              搜索
            </el-button>
          </el-form-item>

          <el-form-item>
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icondaochu"
              @click="download"
            >
              <span class="download">导出</span>
            </el-button>
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icondaoru"
              @click="blackListImport"
            >
              <span class="opetareText">导入</span>
            </el-button>
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icontianjia"
              @click="addNew"
            >
              <span class="opetareText">添加</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <el-table
          ref="tableBox1"
          border
          :max-height="tableHeight"
          @selection-change="handleSelectionChange"
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            v-if="isShowUpdate && userType == 'AREAMANAGE'"
            type="selection"
            width="55"
          ></el-table-column>
          <el-table-column
            prop="year"
            label="年份"
            :formatter="formatTd"
            width="120"
          />
          <el-table-column
            prop="batchNo"
            label="批次号"
            :formatter="formatTd"
            width="120"
          />
          <el-table-column
            prop="companyName"
            label="企业名称"
            align="center"
            width="120"
            :formatter="formatTd"
          />
          <el-table-column
            prop="uscc"
            label="统一社会信用代码或工商注册号"
            :formatter="formatTd"
            min-width="240px"
          />
          <el-table-column
            prop="boss"
            label="法定代表人姓名"
            align="center"
            :formatter="formatTd"
            min-width="180px"
          />
          <el-table-column
            prop="bossIdcard"
            label="法定代表人或自然人身份证件号码"
            align="center"
            :formatter="formatTd"
            min-width="260px"
          />
          <el-table-column
            prop="reason"
            label="列入名单事由"
            width="120"
            :formatter="formatTd"
          />
          <el-table-column
            prop="arrearage"
            label="涉及金额(元)"
            width="120"
            :formatter="formatTd"
          />
          <el-table-column
            prop="effectiveStartDate"
            label="列入日期"
            width="120"
            align="center"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              {{ common.GMTFormat(scope.row.effectiveStartDate, 1) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="thatDepartment"
            label="认定部门"
            width="120"
            align="center"
            :formatter="formatTd"
          />
          <el-table-column
            prop="punishNumber"
            label="文书号"
            width="120"
            align="center"
            :formatter="formatTd"
          >
          </el-table-column>
          <el-table-column
            prop="effectiveEndDate"
            label="退出日期"
            width="120"
            align="center"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              {{ common.GMTFormat(scope.row.effectiveEndDate, 1) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" fixed="right" width="210">
            <template slot-scope="scope">
              <el-link type="primary" @click="toDetail(scope.row)"
                >查看详情</el-link
              >
              <el-link type="primary" @click="editItems(scope.row)"
                >修改</el-link
              >
              <el-link type="primary" @click="deleteItems(scope.row)"
                >删除</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <Pagination
          ref="pagination"
          @getpageSize="getpageSize"
          @getpageNo="getpageNo"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
      <el-dialog
        title="导入黑名单企业"
        :visible="visible"
        :close-on-click-modal="false"
        @close="closeDialog"
        width="600px"
        :modal-append-to-body="false"
        :close-on-press-escape="false"
        class="dialogForm"
        :append-to-body="true"
      >
        <el-form
          :model="info"
          :rules="rules"
          ref="formData"
          label-width="100px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="年份" prop="year">
                <el-date-picker
                  v-model="info.year"
                  type="year"
                  value-format="yyyy"
                  placeholder="请选择"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="批次号" prop="batchNo">
                <el-input
                  v-model="info.batchNo"
                  style="width: 230px"
                  clearable=""
                  placeholder="请输入"
                  class="caseCompTitleInput"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="mainConImport">
          <div class="mainConImportUp">
            选择导入文件
            <el-input
              class="mainConImportUpInput"
              readonly
              v-model="fileName"
            ></el-input>
            <div class="uploadBox">
              <el-button class="uploadImg">选择上传文件</el-button>
              <div class="upLoadDom">
                <form id="ExcelAgreement">
                  <input
                    type="file"
                    id="salaryExcelAgr"
                    name="file"
                    @change="waterImportfileChange"
                  />
                </form>
              </div>
            </div>
            <!-- 下载《欠薪诉求模板》 -->
            <div class="mainConImportTips">
              请按照模板导入,点击
              <el-link class="downloadTip" @click="downImployee"
                >下载 《黑名单企业模板》</el-link
              >
            </div>
          </div>
        </div>
        <div class="caseCompBtn" slot="footer">
          <el-button
            type="primary"
            v-sdc
            :loading="isSaveLoading"
            class="commonBut saveBtn"
            @click="save"
            >保存</el-button
          >
          <el-button type="default" v-sdc class="commonBut" @click="closeDialog"
            >取消</el-button
          >
        </div>
      </el-dialog>
    </div>
    <black-dialog
      :id="itemId"
      @callback="handleDialog"
      :dialogTitle="dialogTitle"
      :visible="dialogVisible"
    />
    <el-dialog
      title="上传失败"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="uploadCloseDialog"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
    >
      <div class="errorNoticeBox">
        <i class="icon iconfont iconshibai1"></i>
      </div>
      <div v-html="errorNotice" class="errorBox"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="uploadCloseDialog" class="save"
          >确认</el-button
        >
        <el-button @click.native="uploadCloseDialog" class="cancel"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import common from '@/kits/common'
import scrollTable from '@/mixin/scrollTable.js'

import blackDialog from './blackDialog.vue'
export default {
  name: 'blackOrders',
  mixins: [scrollTable],
  data() {
    return {
      titleText: '拖欠农民工工资"黑名单"',
      loading: false,
      tableList: [],
      requestUrl: 'api-r/cb/page',
      filterField: {
        keyword: '',
      },
      pageSize: 20,
      pageNo: 1,
      dialogVisible: false,
      itemId: '',
      dialogTitle: '新增企业黑名单',
      info: {
        batchNo: '',
        year: '',
      },
      rules: {
        batchNo: [
          { message: '批次号不能为空', trigger: 'blur', required: true },
        ],
        year: [{ message: '请选择年份', trigger: 'change', required: true }],
      },
      fileName: '',
      visible: false,
      isSaveLoading: false,
      formVisible: false,
      errorNotice: '',
    }
  },
  components: { blackDialog },
  mounted() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  methods: {
    addNew() {
      this.itemId = ''
      this.dialogTitle = '新增企业黑名单'
      this.dialogVisible = true
    },
    editItems(item) {
      this.itemId = item.id
      this.dialogTitle = '修改企业黑名单'
      this.dialogVisible = true
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    toDetail(item) {
      this.$router.push({
        path: '/home/kMCaseComplaint/blackOrdersDetail',
        name: 'blackOrdersDetail',
        query: {
          id: item.id,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/kMCaseComplaint/blackOrders',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    deleteItems(item) {
      let that = this
      this.$confirm('确定是否删除该条记录?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          that.axios.post('api-r/cb/delete', { id: item.id }).then((res) => {
            if (!res.data.hasError) {
              that.$message.success('删除成功')
              that.searchList()
            } else {
              that.$message.warning(res.data.errorMsg)
            }
          })
        })
        .catch(() => {})
    },
    handleDialog(val) {
      this.dialogVisible = false
      if (val.success) {
        this.searchList()
      }
    },
    download() {
      window.location.href =
        common.commonApi +
        'api-r/cb/export?keyword=' +
        this.filterField.keyword +
        '&access_token=' +
        localStorage.getItem('access_token')
    },
    blackListImport() {
      // this.$router.push("/home/kMCaseComplaint/kmBlackListImport");
      // this.$store.commit("CHANGE_SLIDER_NAME", {
      //     oldUrl: "home/kMCaseComplaint/blackOrders",
      //     newUrl: this.$router.currentRoute.fullPath,
      // });
      this.$nextTick(() => {
        this.$refs.formData.resetFields()
      })
      this.visible = true
      this.fileName = ''
      this.info = {
        batchNo: '',
        year: '',
      }
      $('#salaryExcelAgr').val('')
    },
    closeDialog() {
      this.visible = false
      this.info = {
        batchNo: '',
        year: '',
      }
      $('#salaryExcelAgr').val('')
    },
    waterImportfileChange(e) {
      this.fileName = ''
      var url = window.location.href
      var Filedata = e.target.value
      var files = e.target.files[0]
      if (Filedata == '' || Filedata == undefined) {
        return
      }
      if (!/\.(xls|xlsx)$/.test(Filedata)) {
        this.$message({
          message: 'excel类型必须是.xls,xlsx中的一种',
          type: 'warning',
        })
        return
      }
      this.fileName = files.name
    },
    save() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          this.uploadImployee()
        } else {
          this.isSaveLoading = false
          return false
        }
      })
    },
    uploadImployee() {
      let that = this
      if (!that.fileName == '') {
        that.active = 1
        that.uploadFileByAjaxSubmit('api-r/cb/import', that.success, that.error)
      } else {
        this.isSaveLoading = false
        that.$message({
          type: 'warning',
          message: '请先选择上传文件!',
        })
      }
    },
    uploadFileByAjaxSubmit(url, successCallBack, errorCallBack) {
      const that = this
      var token = localStorage.getItem('access_token')
      var options = {
        url: common.uploadUrl + url,
        type: 'POST',
        dataType: 'json',
        headers: { Authorization: 'Bearer ' + token },
        data: that.info,
        success: function (data) {
          $('#salaryExcelAgr').val('')
          successCallBack(data)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $('#salaryExcelAgr').val('')
          errorCallBack(XMLHttpRequest, textStatus, errorThrown)
        },
      }

      //三种方式均可
      $('#ExcelAgreement').ajaxSubmit(options)
      return false
    },
    success(data) {
      if (!data.hasError) {
        this.isSaveLoading = false
        this.fileName = ''
        this.visible = false
        this.info = {
          batchNo: '',
          year: '',
        }
        this.$message({
          message: data.msg,
          type: 'success',
        })
        this.$nextTick(function () {
          this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
        })
      } else {
        this.errorNotice = data.errorMsg
        this.formVisible = true
        this.isSaveLoading = false
        this.fileName = ''
        $('#salaryExcelAgr').val('')
      }
    },
    //根据状态码判断是否是401
    error(XMLHttpRequest, textStatus, errorThrown) {
      this.isSaveLoading = false
      if (XMLHttpRequest.status === '401' || XMLHttpRequest.status === '403') {
        localStorage.setItem('access_token', '')
        localStorage.setItem('refresh_token', '')
        localStorage.setItem('userName', '')
        // 只有在当前路由不是登录页面才跳转
        if (router.currentRoute.path !== '/login/loginFirst') {
          router.replace({
            path: '/login/loginFirst',
          })
        }
        //清除tab栏数据
        this.$store.state.sliderBar = []
        localStorage.removeItem('sliderBar')
      } else {
        this.$message({
          message: '数据请求失败',
          type: 'warning',
        })
      }
    },
    downImployee() {
      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/findurl',
        data: { name: 'companyBlack' },
      })
        .then((response) => {
          if (!response.data.hasError) {
            window.location.href = response.data.result.url
          }
        })
        .catch((error) => {})
    },
    uploadCloseDialog() {
      this.formVisible = false
    },
  },
}
</script>

<style scoped lang="less">
.mainCon {
  height: calc(100% - 67px);
  &Import {
    p {
      font-family: SourceHanSansCN-Medium;
      font-size: 28px;
      color: #333333;
      text-align: center;
      font-weight: bold;
      margin: 60px 0;
    }
    &Up {
      text-align: center;
      //   height: 36px;
      .el-input {
        max-width: 300px;
      }
    }
    &Tips {
      text-align: left;
      height: 14px;
      line-height: 14px;
      font-size: 14px;
      color: #333;
      margin: 24px 0 40px;
      vertical-align: middle;
      /deep/.el-link--inner {
        color: #409eff;
      }
    }
  }
}
.uploadBox {
  display: inline-block;
  position: relative;
  .uploadImg {
    width: 126px;
    height: 36px;
    padding: 0px;
    color: #009588;
    border: 1px solid #009588;
    cursor: pointer;
  }
  .upLoadDom {
    position: absolute;
    width: 126px;
    height: 36px;
    top: 0;
    left: 0;
    opacity: 0;
    line-height: 0px;
    form {
      input {
        width: 96px;
        height: 36px;
        line-height: 0px;
        cursor: pointer;
      }
    }
  }
}
/deep/.el-dialog__footer {
  height: 75px !important;
  padding: 20px !important;
  .commonBut {
    width: 90px;
  }
}

/deep/ .uscc .el-form-item__label {
  line-height: 19px;
}
.errorNoticeBox {
  text-align: center;
  margin-bottom: 24px;
  i {
    color: red;
    font-size: 50px;
  }
}
.errorBox {
  line-height: 24px;
}
</style>
